Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    email: ''  // 可选邮箱字段
  },
  onPullDownRefresh(){
    this.onLoad()
},
  register() {
    const { username, password, confirmPassword, phone, email } = this.data;
    const app = getApp();

    // 检查表单是否完整
    if (!username || !password || !confirmPassword || !phone) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    // 检查两次输入的密码是否一致
    if (password !== confirmPassword) {
      wx.showToast({
        title: '密码不一致',
        icon: 'none'
      });
      return;
    }

    // 组装请求数据，若邮箱为空则不传递
    const requestData = { username, password, phone };
    if (email) requestData.email = email;

    // 发起注册请求
    wx.request({
      url: app.apiUrl + '/users/register',
      method: 'POST',
      data: requestData,
      success: (res) => {
        if (res.data.code !== 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'error'
          });
        } else {
          wx.showToast({
            title: '注册成功',
            icon: 'success',
            success: () => {
              wx.redirectTo({
                url: '/pages/user/login/login'
              });
            }
          });
        }
      }
    });
  }
});
